package com.android.fragmentdemo.definervlayoutmanager;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;

public class CardLayoutManager extends RecyclerView.LayoutManager {

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);

        removeAllViews();
        detachAndScrapAttachedViews(recycler);

        int itemCount = getItemCount();
        int initIndex = itemCount - CardConfig.SHOW_MAX_COUNT;
        if (initIndex < 0) {
            initIndex = 0;
        }

        for (int i = initIndex; i < itemCount; i++) {
            View child = recycler.getViewForPosition(i);
            addView(child);
            measureChildWithMargins(child, 0, 0);
            int realWidth = getDecoratedMeasuredWidth(child);
            int realHeight = getDecoratedMeasuredHeight(child);
            int widthPadding = (int) ((getWidth() - realWidth) / 2.0f);
            int heightPadding = (int) ((getHeight() - realHeight) / 2.0f);
            layoutDecoratedWithMargins(child, widthPadding, heightPadding, widthPadding + realWidth, heightPadding + realHeight);
            int level = itemCount - i - 1;
            if (CardConfig.SHOW_MAX_COUNT - 1 == level) {
                level--;
            }
            child.setTranslationY(level * CardConfig.TRANSLATION_Y);
            float scaleValue = 1 - level * CardConfig.SCALE;
            child.setScaleX(scaleValue);
            child.setScaleX(scaleValue);
        }
    }
}
